import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage } from 'element-plus'
import { getPlatformUser, getMoneyLimit } from '@/api/user'
import { checkRoles } from '@/stores/roles'
import _ from 'lodash-es'

export const useSellStore = () => {
  const userStore = useUserStore()

  const state = reactive({
    users: [],
    groups: [],
    userId: null,
    platformUsers: null,
    userdialogshow: {
      show: false,
      type: 'radio',

    },
    radiouser: '',
    checkuserAll: false,
    activecheckuserOrder: {},
    options: [],
    query: {
      platform_from: 'hga',
      select_type_from: 'event_type',
      event_type_from: 'today',
      league_from: 'all',
    },

    match: {
      loading: false,
      list: [],
      options: {},
      intervalId: null,
    },
    saveorder: {
      list: [],
      total: 0,
      page: 1,
      page_size: 20,
      showloading: false,
      expand: ''
    },

    orderData: {
      type: 0, // 0、即时 1、预约

      match: null,

      list: {}, // 即时
      reservationList: {}, // 预约

      subscribe: {
        show: false,
      },
    },

    other: {
      data: null,
      match: null,
      otherType: null,
      intervalId: null,
      showAll: false,
    },

    permissionBctypes: {},

    matchdetail: {
      show: false,
      match: {}
    },


  })

  onMounted(async () => {
    initData()
  })

  onUnmounted(() => {
    clearInterval(state.match.intervalId)
    clearInterval(state.other.intervalId)
  })

  // 获取任务数据
  const getMatchList = (loading = true) => {
    if (loading) state.match.loading = true
    clearInterval(state.match.intervalId)
    http
      .post('/match/match_select', {
        page: 1,
        page_size: 10,
        ...state.query,
      })
      .then(res => {

        if (!state.matchdetail.show) {
          clearInterval(state.match.intervalId)
          state.match.intervalId = setInterval(() => getMatchList(false), 3000)
        } else {
          clearInterval(state.match.intervalId)
        }

        state.match.list = res.data.match_data.match_list
        state.options = res.data.options.map(item => {
          state.query[item.type] = item.choiced
          return item
        })
      })
      .finally((error) => {

        state.match.loading = false
      })
  }

  // 获取用户
  const getUserList = () => {
    state.userId = null

    // return http
    //   .get('/qluser_config/list', {
    //     params: {
    //       page: 1,
    //       page_size: 9999,
    //       task_type: 'chuhuo',
    //       status: 1
    //     },
    //   })
    //   .then(res => {
    //     state.users = res.data.list?.map(item => {
    //       return {
    //         ...item,
    //         label: item.config_name,
    //         value: item.id,
    //       }
    //     })

    //     if (state.users?.length) state.userId = state.users[0].id
    //   })
  }

  const getGroupsList = () => {
    state.userId = null
    return http
      .get('/group/group_list', {
        params: {
          page: 1,
          page_size: 9999,
          status: 1
        },
      })
      .then(res => {
        state.users = res.data.list?.map(item => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          }
        })

        if (state.users?.length) state.userId = state.users[0].id
      }).catch((error) => {
        console.log(error);

      })
  }

  // 获取用户配置
  const getUserConfig = () => {
    if (!state.userId) return

    getPlatformUser({ id: state.userId }).then(res => {

      state.platformUsers = res.data

    })
  }

  // 任务搜索
  const handleSearch = searchIndex => {
    let searchData = {}
    state.options.map((item, index) => {
      if (searchIndex != state.options.length - 1 && index == state.options.length - 1) {
        searchData[item.type] = 'all'
      } else {
        searchData[item.type] = item.choiced
      }
    })

    state.query = searchData

    initData()
  }

  // 选择比赛结果
  const selectMetchResult = async (item, match) => {


    await getUserConfig()
    state.userdialogshow.show = false
    // 选择了新的比赛
    if (state.orderData.match?.ids != match.ids) {
      state.orderData.list = {}
      state.orderData.reservationList = {}
      state.orderData.match = cloneDeep(match)
    }

    if (!state.orderData.list[item.pk_odds_key]) {
      // 获取右侧其他盘口
      http
        .post(`/match/other_platform_odd_list`, {
          bc_type: match.bc_type,
          event_type: match.event_type,
          league_id: match.league_id,
          home_id: match.home_id,
          away_id: match.away_id,
          pk_odds_key: item.pk_odds_key,
          nav_data: item.nav_data,
          odd: item.odd,
          sport_type: match.sport_type
        })
        .then(res => {
          console.log(res.data);
          
          let a = []

          res.data.forEach(item => {
            state.permissionBctypes.forEach(item2 => {
              if (item.bc_type == item2.value) {

                if (checkRoles(userStore.user.roles, 'all_bookies')) {
                  a.push(item)
                } else {
                  if (item.bc_type == match.bc_type) {
                    a.push(item)
                  }
                }
              }
            });
          });


          a.min_odd = a.odd
          a.max_odd = 1000
          a.map(item => {
            item.checked = false
          })

          state.orderData.list[item.pk_odds_key] = _.cloneDeep(a)
          state.orderData.reservationList[item.pk_odds_key] = _.cloneDeep(a)
          console.log(state.orderData.list);

          Object.keys(state.orderData.list).forEach(key => {
            if (key == item.pk_odds_key) {
              state.orderData.list[key].forEach(item => {
                if (!key.includes('M') && checkRoles(userStore.user.roles, 'reverse')) {
                  // 是否是反向单
                  item.directionorder = false
                  // 是否有反向按钮
                  item.isdirection = true
                  // 反向value
                  item.directionValue = false
                } else {
                  item.directionorder = false
                  item.isdirection = false
                  item.directionValue = false
                }



                item.min_odd = item.odd
                item.max_odd = 1000
              });
            }

          });

        })
    } else {
      delete state.orderData.list[item.pk_odds_key]
      delete state.orderData.reservationList[item.pk_odds_key]
    }
  }

  const selectDirectionMatch = (row, order) => {
    console.log(row);
    console.log(order);


    let a = []

    row.forEach(item => {
      state.permissionBctypes.forEach(item2 => {
        if (item.bc_type == item2.value) {
          a.push(item)
        }
      });
    });


    a.min_odd = a.odd
    a.max_odd = 1000
    a.map(item => {
      item.checked = true
    })
    let b = _.cloneDeep(a)
    console.log(b);

    b.forEach(item => {
      if (item.bc_type == order.bc_type) {
        item.min_odd = item.odd
        item.max_odd = 1000
        item.user_config_id = ''
        item.users_group = {}
        console.log(state.orderData.list[order.pk_odds_key]);
        let c = JSON.parse(JSON.stringify(state.orderData.list[order.pk_odds_key]))
        c.forEach((item2, index2) => {
          if (item2.bc_type == order.bc_type) {
            item.directionorder = true
            item.isdirection = false
            item.directionValue = false

            state.orderData.list[order.pk_odds_key].splice(index2 + 1, 0, item);
          }
        });
      }
    });

    console.log(state.orderData.list);



    // state.orderData.list[oddskey] = _.cloneDeep(a)
    // state.orderData.reservationList[oddskey] = _.cloneDeep(a)

    // Object.keys(state.orderData.list).forEach(key => {
    //   if (key == oddskey) {
    //     state.orderData.list[key].forEach(item => {
    //       if (!key.includes('M')) {
    //         // 是否是反向单
    //         item.directionorder = true
    //         // 是否有反向按钮
    //         item.isdirection = false
    //         // 反向value
    //         item.directionValue = false
    //       } else {
    // item.directionorder = false
    // item.isdirection = false
    // item.directionValue = false
    //       }


    //       // item.min_odd = item.odd
    //       // item.max_odd = 1000
    //     });
    //   }

    // });

    // console.log(state.orderData);
  }

  // 清空
  const clear = () => {
    state.orderData.match = null
    state.orderData.list = {}
    state.orderData.reservationList = {}
  }

  async function initData() {
    clear()

    clearInterval(state.match.intervalId)
    clearInterval(state.other.intervalId)

    getMatchList()
    getorderlist()
    await getGroupsList()
    // await getUserList()
    // getUserConfig()

    if (localStorage.isDev) return


  }

  // 预定
  const showSubscribe = data => {
    state.orderData.subscribe.data = data
    state.orderData.subscribe.show = true
  }

  const onChangeUser = async () => {
    const list = state.orderData.type == 0 ? state.orderData.list : state.orderData.reservationList

    for (let i = 0; i < list.length; i++) {
      const orders = list[i]

      for (let i = 0; i < orders.length; i++) {
        const order = orders[i]

        order.max_stake = res.data.max_stake
        order.min_stake = res.data.min_stake
        order.odd = res.data.odd
      }
    }

    await getUserConfig()
  }

  function getOrderInfo(order) {
    let body = {
      member_id: order.userId,
      user_type: 'member',
      nav_data: order.nav_data,
      pk_odds_key: order.pk_odds_key,
    }

    getMoneyLimit(body)
      .then(res => {
        order.max_stake = res.data.max_stake
        order.min_stake = res.data.min_stake
        order.odd = res.data.odd
      })
      .catch(() => {
        order.max_stake = null
        order.min_stake = null
      })
  }

  const selectOther = (typeItem, match) => {
    clearInterval(state.other.intervalId)

    if (state.other.otherType == typeItem.value && state.other.match.match_id == match.match_id) {
      delete state.other.otherType
      delete state.other.match
    } else {
      state.other.otherType = typeItem.value
      state.other.match = match
      getOtherData()

      if (localStorage.isDev) return
      // state.other.intervalId = setInterval(() => getOtherData(false), 3000)
    }
  }

  const getOtherData = (loading = true) => {
    if (loading) state.other.loading = true

    const { match } = state.other

    http
      .post(`/match/get_now_odds_all_details`, {
        bc_type: match.bc_type,
        event_type: match.event_type,
        match_id: match.match_id,
        ids: match.ids,
        sport_type: match.sport_type
      })
      .then(res => {
        // 让球数据处理
        if (res.data.odds_data) {
          const rqData = []

          for (const key in res.data.odds_data) {
            const typeItem = res.data.odds_data[key]
            const newTypeItem = {
              label: {
                full: '全场',
                half: '上半场',
              }[key],
              results: [],
              showAll: true,
            }

            if (!newTypeItem.label) continue

            for (const key in typeItem) {
              const resultItem = typeItem[key]
              const newResultItem = {
                label: {
                  OU: '大小',
                  // OUC: '客队进球数',
                  // OUH: '主队进球数',
                  R: '让球',
                }[key],
                homeData: [],
                awayData: [],
              }

              if (!newResultItem.label) continue

              resultItem.forEach(item => {
                newResultItem['homeData'].push(item.odds[0])
                newResultItem['awayData'].push(item.odds[1])
              })
              console.log(newResultItem);


              newTypeItem.results.push(newResultItem)
            }

            rqData.push(newTypeItem)
          }

          res.data._rqData = rqData
        }


        state.other.data = res.data
        console.log(state.other);
      })
      .finally(() => {
        state.other.loading = false
      })
  }

  const getorderlist = () => {
    state.saveorder.showloading = true
    let body = {
      page: state.saveorder.page,
      page_size: state.saveorder.page_size,
      scheme_task_code: ''
    }
    http.post(`/order/order_list_byscheme`, body).then((res) => {
      state.saveorder.list = res.data.order_list
      state.saveorder.total = res.data.total
      state.saveorder.page = res.data.page
      state.saveorder.page_size = res.data.page_size
      state.saveorder.showloading = false

    })
  }

  const changeOrdermode = (order) => {
    console.log(order);
    order.place_mode = ''
    // http.get(`/order/get_place_members_count?bc_type=${order.bc_type}&group_id=${state.userId}`).then((res) => {
    //   console.log(res);
    //   if (order.order_mode == 'count_user') {
    //     if (res.data.member_count >= 2) {
    //       order.membercounts = res.data.member_count
    //       order.member_count = 2
    //       order.member_count_show = true
    //     } else {
    //       order.member_count = 1
    //       order.order_mode = 'one_user'
    //       order.member_count_show = false
    //       ElMessage({
    //         message: '暂无更多账号可选',
    //         type: 'warning',
    //       })
    //     }

    //   } else {
    //     order.member_count_show = false
    //     order.member_count = 1
    //   }
    // })


  }





  return {
    state,

    clear,
    initData,
    handleSearch,
    selectMetchResult,
    showSubscribe,
    getUserConfig,
    onChangeUser,
    getOrderInfo,
    selectOther,
    getOtherData,
    getorderlist,
    changeOrdermode,
    selectDirectionMatch,
    getMatchList
  }
}
